package com.example.demo.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@WebFilter(urlPatterns = "/*")
public class AccountFilter implements Filter {

    //不需要登录的uri

    private final String[] IGNORE_URI = {"/index", "/account/validataAccount", "/css", "/js", "/account/login", "/images"};

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();

        //// 当前访问的URI是不是 在Ignore列表里
        boolean pass = canPassIgnore(uri);
        System.out.println("getSession uri:" + uri + "---" + pass);
        if (pass) {
            //在的话放行
            filterChain.doFilter(request, response);
            return;
        }
        // 是否已登录，从session里找 Account
        Object account = request.getSession().getAttribute("account");
        System.out.println("getSession account:" + account);
        if (null == account) {
            //没登录跳转登录页面
            System.out.println("getSession account11:" + account);
            response.sendRedirect("/account/login");
            return;
        }

        filterChain.doFilter(request, response);
    }

    private boolean canPassIgnore(String uri) {

        // /index = uri

        // 判断 访问的URI 起始部分 是否包含 Ignore
        // 下级目录资源也能访问

        for (String val : IGNORE_URI) {

            if (uri.startsWith(val)) {
                return true;
            }
        }
        return false;
    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //加载Filter启动之前需要的资源
        System.out.println("-----------AccountFilter init-");
    }
}
